import { onMounted, Ref, ref } from "vue";
import Screenfull from "screenfull";

export default function (target?: string | Ref, options?: FullscreenOptions) {
	const isScreenFull = ref(false),
		isEnabled = ref(Screenfull.isEnabled),
		targetRef = ref(target || (target && document?.querySelector(target)));

	onMounted(() => {
		Screenfull.isEnabled &&
			Screenfull.onchange(() => {
				isScreenFull.value = !isScreenFull.value;
			});
	});

	const isSupport = () => {
		!isEnabled.value && window.$message.error("浏览器不支持全屏！");
		return isEnabled.value;
	};

	/**
	 * Enter full screen
	 */
	const full = () => {
		isSupport() && Screenfull.isEnabled && Screenfull.request(targetRef.value, options);
	};

	/**
	 * Exit full screen
	 */
	const exit = () => {
		isSupport() && Screenfull.isEnabled && Screenfull.exit();
	};

	/**
	 * Enter or Exit full screen
	 */
	const toggle = () => {
		(isScreenFull.value ? exit : full)();
	};

	return {
		isScreenFull,
		isEnabled,
		full,
		exit,
		toggle,
	};
}
